<?php
/**
 * Created by PhpStorm.
 * User: Argon
 * Date: 2016/12/28
 * Time: 11:30
 */

namespace App\Controller\Index;


use Common\Model\MemberMessageModel;
use Common\Model\MemberModel;
use Common\Model\MemberOtherPlatformModel;
use Common\Model\MemberWeixinModel;
use Common\Model\MicroShopModel;
use Common\Model\TarentoModel;
use Org\Net\Http;
use Think\Controller;

class WechatServerController extends Controller
{


    public static function getClientPlatformAndSystem()
    {
        $headers = getallheaders();
        $headerClientSystem = $headers['clientSystem'];
        $clientSystem = 0;
        $clientPlatform = 0;
        switch ($headerClientSystem) {
            case 'ios':
                $clientSystem = 1;
                $clientPlatform = 1;
                break;
            case 'android':
                $clientSystem = 2;
                $clientPlatform = 1;
                break;
            case 'wx-micro-shop':
                $clientSystem = 3;
                $clientPlatform = 4;
                break;
            case 'web-pc':
                $clientSystem = 3;
                $clientPlatform = 3;
                break;
            case 'web-wap':
                $clientSystem = 3;
                $clientPlatform = 2;
                break;
            default:
                break;
        }
        return ['clientSystem' => $clientSystem, 'clientPlatform' => $clientPlatform];
    }

    public static function getMemberIdByOtherData($openType, $openSecretid)
    {
        $model = new MemberWeixinModel();
        $record =  $model->where("unique_code='$openSecretid'")->field("meber_id")->find();
        if (empty($record)) {
            return -1;
        }
        return $record['meber_id'];
    }

    /**
     * 注册一个用户
     * @param array $data
     * @return int 新注册的用户 ID
     */
    public static function registerMember($data)
    {
        $memberModel = new MemberModel();

        $res = $memberModel->add($data);

        return $res;
    }

    public static function deleteNoBindData($openType, $openSecretid)
    {
        $model = new MemberOtherPlatformModel();
        $res = $model->where(["open_type" => ['eq', $openType], 'open_secretid' => ['eq', $openSecretid]])->delete();
        return $res;
    }

    public function loginFromOtherPlatform($otherLoginPlatform, $mebmerOtherPlatformData, $shop_id)
    {
        file_put_contents('/alidata/www/weiphp/aaaaaaaa4.txt',print_r($mebmerOtherPlatformData,true),FILE_APPEND);

        $a = explode('u',$mebmerOtherPlatformData['nickname']);
        if($a){
            $a = array_filter($a);
            $str = '';
            for($i=1;$i<=count($a);$i++){
                $str .= '\u'.$a[$i];
            }
            $mebmerOtherPlatformData['nickname'] = unicode_decode($str);
        }

        if (empty($mebmerOtherPlatformData) || empty($mebmerOtherPlatformData['haiooUnionid'])) {
            return ['code' => 1034];
        }

        $shop_id = $shop_id > 0 ? $shop_id : 0;
        $openSecretid = $mebmerOtherPlatformData['haiooUnionid'];
        $typeMap = [
            'weixin' => '1',
            'qq' => '2',
            'sina' => '3',
            'web' => '4',
        ];
        $memberId = self::getMemberIdByOtherData($typeMap[$otherLoginPlatform], $openSecretid);

        if ($memberId !== -1 && !($memberId > 0)) {
            //已存在，但是没有绑定会员，这种是其它端微信登陆且没有绑定手机的，这里可以删除掉重新生成一个
            self::deleteNoBindData($typeMap[$otherLoginPlatform], $openSecretid);
            $memberId = -1;
        }

        $otherPlatformLogo = '';
        if ($otherLoginPlatform == 'weixin') {
            $otherPlatformLogo = empty($mebmerOtherPlatformData['headimgurl']) ? 'http://wx.52ywy.com/images/default_head.png' : $mebmerOtherPlatformData['headimgurl'];
        }
        $isNew = false;
        if ($memberId === -1) {//新会员，自动帮他注册
            $model = M();
            $model->startTrans();
            $data['name'] = $mebmerOtherPlatformData['userinfo']['nickname'];
            $data['login_time'] = date('Y-m-d H:i:s',time());
            $data['parent_id'] = $shop_id;
            $data['sex'] = $mebmerOtherPlatformData['userinfo']['sex'];
            $data['logo']   = $mebmerOtherPlatformData['userinfo']['headimgurl'];
            $data['create_time'] = date('Y-m-d H:i:s',time());
            $m_id = $model->table(C('DB_PREFIX').'member')->add($data);

            $w_data['unique_code'] = $mebmerOtherPlatformData['userinfo']['openid'];
            $w_data['member_id'] = $m_id;
            $w_data['data'] = json_encode($mebmerOtherPlatformData);
            $w_data['create_time'] = date('Y-m-d H:i:s',time());
            $w_id = $model->table(C('DB_PREFIX').'member_weixin')->add($w_data);
            if ($memberId && $m_id && $w_id ) {
                $model->commit();

            } else {
                $model->rollback();
                return (['code' => 300, 'msg' => '登录失败，请稍后再试']);
            }
        }
       $model = new MemberModel();
       $memberInfo =  $model->where("userid=$memberId")->find();
        $isNew = true;
            //注册会员
        $memberInfo['otherPlatformLogo'] = $memberInfo['logo'];
        if ($otherPlatformLogo != '') {
            $memberInfo['otherPlatformLogo'] = $otherPlatformLogo;
        }
        $memberInfo['isNew'] = $isNew;
        $memberInfo['memberId'] = $memberInfo['userid'];
        return $memberInfo;
    }







    /**
     * 获取登陆成功返回的数据信息
     * @param unknown $memberId
     */
    protected function getLoginedSuccessResData($memberId)
    {
        if ($memberId <=0) {
            outPut(['code'=>1035]);
        }
        $memberModel = new MemberModel();
        $userInfo = $memberModel->find($memberId);
        if (is_null($userInfo)) {
            outPut(['code'=>1035]);
        }
        //获取用户是否开店
        $haveMicroShop = false;
        $tarentModel = new TarentoModel();
//        $tarentInfo = \App\Models\Tarento::getInfoByMemberId($memberId);
        $tarentInfo = $tarentModel->where("member_id = $memberId")->find();
        if ($tarentInfo['have_micro_shop'] > 0) {
            $haveMicroShop = true;
        }
        $belongToShopId = $memberId;
        if (!$haveMicroShop) {
            //没店铺，拿上一级
            $relations = explode(',', $tarentInfo['relations']);
            foreach ($relations as $k => $v) {
                if ($v == $belongToShopId) {
                    $belongToShopId = $relations[$k - 1];
                }
            }
        }

        $res = [
            'memberId' => $userInfo['userid'],
            'userName' => $userInfo['username'],
            'mobile'   => $userInfo['mobile'],
            'name'     => $userInfo['name'],
            'logo'     => $userInfo['logo'],
            'haveMicroShop'   => $haveMicroShop,
            'memberSignature' => md5($userInfo['userid'].'*&*GI3^452%$&'),
            'belongToShopId'  => $belongToShopId,
            'is_web'          =>$userInfo['is_web']
        ];
        return $res;
    }



}